package top.ewind.controller.admin.system;

import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;

import top.ewind.controller.common.AdminRootCtrl;
import top.ewind.jfinal.ext.authorize.Authorize;
import top.ewind.util.SecurityUtil;
@Authorize(name = "2", value = "用户管理")
public class UserCtrl extends AdminRootCtrl {	

	public void index(){
		render("index.html");
	}

	public void profile(){
		String filter = SecurityUtil.sqlFilter(getPara("param", ""));
		renderJson(Db.paginate(getParaToInt("page",1),getParaToInt("rp",10),"SELECT u.*, r.rname ", "from sys_admin u left join sys_role r on u.rid = r.id where true"+filter));
	}
	
	@Authorize(name = "2_3", value = "删除")
	public void delete(){
		boolean ret = false;
		if(StrKit.notBlank(getPara("id"))){
			ret = Db.deleteById("sys_admin",getPara("id"));
		}
		if(ret)renderJson("msg","success");
		else renderJson("msg","删除失败，请重试！");
	}

	@Authorize(name = "2_1", value = "新增")
	public void add(){
		setAttr("rolelist",Db.find("select * from sys_role where nid = ?",getSessionAttr("nid")));
		render("edit.html");
	}

	@Authorize(name = "2_2", value = "修改")
	public void edit(){
		int nid = getSessionAttr("nid");
		Record admin = Db.findById("sys_admin",getPara(0));
		if(admin!=null){
			setAttr("sysAdmin",admin);
			setAttr("rolelist",Db.find("select * from sys_role where nid = ?",nid));
			render("edit.html");
		}
		else renderNull();
	}

	public void save(){
		boolean ret = false;
		Record item = Db.findById("sys_admin", getPara("sysAdmin.id"));
		if(item!=null){
			item.set("rid", getPara("sysAdmin.rid")).set("username", getPara("sysAdmin.username")).set("nickname", getPara("sysAdmin.nickname")).set("remark", getPara("sysAdmin.remark")).set("mobile",getPara("sysAdmin.mobile")).set("email", getPara("sysAdmin.email"));
			if(StrKit.notBlank(getPara("sysAdmin.password"))){
				item.set("password", SecurityUtil.md5(getPara("sysAdmin.password")));
			}
			ret = Db.update("sys_admin",item);
		}
		else{
			item = new Record().set("rid", getPara("sysAdmin.rid")).set("password", SecurityUtil.md5(getPara("sysAdmin.password"))).set("username", getPara("sysAdmin.username")).set("nickname", getPara("sysAdmin.nickname")).set("remark", getPara("sysAdmin.remark")).set("mobile",getPara("sysAdmin.mobile")).set("email", getPara("sysAdmin.email"));
			ret = Db.save("sys_admin",item);
		}
		if(ret)renderJson("msg","success");
		else renderJson("msg","保存失败，请重试！");
	}	
}